<?php
defined('_JEXEC') or die();

jimport('joomla.application.component.controllerform');
jimport('joomla.client.ftp');

class Easiv2adminControllerManageInstances extends JControllerForm {
	
	function display() {
		JHTML::stylesheet('easiv2.css', JPATH_COMPONENT.DS.'css');
		
		parent::display();
	}
	
	function redirect() {
		parent::redirect();
	}
	
	function gotoAddExistingInstance() {
		
		JRequest::setVar('view', 'addExistingInstance');
		
		parent::display();
	}
	/**
	 * WHY IS THIS CALLED EVEN AFTER THE METHOD HAS BEEN EXECUTED?????
	 */
	function saveInstance() {
		/**
		 * Validation and saving to database
		 */
		
		/*
		 * setting default values if none were inserted by user
		 */
		if(($name = $_POST['name']) == "")
			$name = 'Default Site';
		
		if(($port = $_POST['port']) == "")
			$port = 21;
		
		$http_address = $_POST['http_address'];
		$ftp_host = $_POST['ftp_host'];
		$host_folder = $_POST['host_folder'];
		$ftp_user = $_POST['ftp_user'];
		$ftp_pass = $_POST['ftp_pass'];
		
		if($ftp_user != "" && $ftp_pass != "" && $ftp_host != "" && $http_address != "" && $ftp_host != "") {
			
			if($this->isFtpValid($ftp_host, $port, $ftp_user, $ftp_pass)) {			
				$db = JFactory::getDBO();
				$query = "INSERT INTO #__easiv2_instances VALUES (DEFAULT, '".$name."', '".$http_address."', '".$ftp_host."', '".$port."', '".$host_folder."', '".$ftp_user."', '".$ftp_pass."');";
				$db->setQuery($query);
				$db->query();
				
				JRequest::setVar('view', 'manageInstances');
				
				echo "<span style=\"color:#0F0\">".JText::_('Instance has been added successfully.')."<br>".$_POST['task']."<br>".$_GET['task']."</span>";
			}
			else {
				echo "<span style=\"color:#F00\">".JText::_('Cannot connect to FTP.')."</span>";
			}
		}
		else {
			echo "<span style=\"color:#F00\">".JText::_('Some information is missing. Please check again.')."</span>";
			echo "<br>".$ftp_user;
			?>
			<script language="javascript" type="text/javascript">
				form = document.forms[0];
				document.write("haha:" + form.elements[0]);

				form.elements['name'].value = "name";
			</script>
			<?php 
		}
		
		parent::display();
	}
	
	/**
	 * 
	 */
	function gotoInstallInstance() {

		JRequest::setVar('view', 'installNewInstance');
		
		parent::display();
	}
	
	function installInstance() {
	
	}
	
	/**
	 * FTP test method
	 */
	function isFtpValid($address, $ftpPort, $user, $pass) {
		
		//TODO get data from database
		$host = $address;
		$port = $ftpPort;
		$ftpUser = $user;
		$ftpPass = $pass;
		
		if($ftp =& JFTP::getInstance($host, $port, null, $ftpUser, $ftpPass)) {
			if($ftp->isConnected()) {
				return true;
			}
			else {
				return false;
			}
		}
		else {
			return false;
		}
	}
}